package com.ideafactory.client.ybservice;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;

import com.ideafactory.client.afinal.NetConstants;
import com.ideafactory.client.beans.ModeBaseInfo;
import com.ideafactory.client.beans.ModeImageList;
import com.ideafactory.client.beans.ModelImageItem;
import com.ideafactory.client.utils.FileConstants;
import com.ideafactory.client.utils.HandTextUtils;
import com.ideafactory.client.utils.JsonForBean;
import com.ideafactory.client.utils.SpUtils;
import com.ideafactory.client.utils.netutils.MyCallBack;
import com.ideafactory.client.utils.netutils.NetUtils;
import com.ideafactory.client.views.StoreHeadPagerAdapter;
import com.ideafactory.client.ybselfservice.R;
import com.ideafactory.client.ybservice.ybviewpager.GoodsBasePager;
import com.ideafactory.client.ybservice.ybviewpager.GoodsDetialAdapter;
import com.ideafactory.client.ybservice.ybviewpager.GoodsDetialPager;
import com.ideafactory.client.ybservice.ybviewpager.GoodsEnsurePager;
import com.ideafactory.client.ybservice.ybviewpager.GoodsPagerSuccessPager;
import com.ideafactory.client.ybservice.ybviewpager.GoodsPayPager;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by LiuShao on 2016/5/24.
 */
@ContentView(R.layout.detial_fragment)
public class YbDetialFragment extends YbBaseFragment {

    private static final String TAG = "YbDetialFragment";

    @ViewInject(R.id.head_detial_viewpager)
    private ViewPager head_detial_viewpager;

    @ViewInject(R.id.iv_header)
    private ImageView iv_header;

    @ViewInject(R.id.goods_detial_viewpager)
    private MyViewPager goods_detial_viewpager;

    private List<GoodsBasePager> goodsBasePagers;
    private GoodsDetialAdapter goodsDetialAdapter;

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

         mhHandler = new Handler() {
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case MSG_TIME:
                        try {
                            cur_index = cur_index % headViewNum;
                            head_detial_viewpager.setCurrentItem(cur_index);
                            cur_index++;
                            mhHandler.sendEmptyMessageDelayed(MSG_TIME, playTime*1000);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        break;
                    case CHANGE_POSITION:
                        controlPosition(GoodsBasePager.MAIN_FRAGMENT,GoodsBasePager.MAIN_FRAGMENT);
                        break;
                }
            }
        };

        Log.e("执行顺序", "YbDetialFragment_onActivityCreated");
        showTime = 60;
        initDetialPager();
        initData();
    }

    private void initDetialPager() {
        goodsBasePagers = new ArrayList<>();
        goodsBasePagers.add(new GoodsDetialPager(getActivity()));
        goods_detial_viewpager.setScanScroll(false);
        goodsBasePagers.add(new GoodsEnsurePager(getActivity()));
        goodsBasePagers.add(new GoodsPayPager(getActivity()));
        goodsBasePagers.add(new GoodsPagerSuccessPager(getActivity()));
        goodsDetialAdapter = new GoodsDetialAdapter(goodsBasePagers);
        goods_detial_viewpager.setAdapter(goodsDetialAdapter);

        goods_detial_viewpager.setOnTouchedScreen(new MyViewPager.OnTouchedScreen() {
            @Override
            public void touched() {
                resetTimer();
            }
        });

        GoodsBasePager.setOnPagerChange(new GoodsBasePager.onPagerChange() {
            @Override
            public void changePositon(int originPosition, int position) {
                controlPosition(originPosition,position);
            }
        });
    }

    private void controlPosition(int origin,int position) {
        System.gc();
        if (position == -1) {
            if (((YbSelfService) getActivity()).toNextPager != null) {
                ((YbSelfService) getActivity()).toNextPager.toNext(YbSelfService.mainPosition);
            }
            if(GoodsDetialPager.onReceivedChangeMain!=null){
                GoodsDetialPager.onReceivedChangeMain.changeToMain();
            }
            if(GoodsEnsurePager.onReceivedChangeMain!=null){
                GoodsEnsurePager.onReceivedChangeMain.changeToMain();
            }
        } else {
            if (position == 0 || position == 1) {
                startTimer();
            }else{
                stopTimer();
            }
            goodsBasePagers.get(position).initData(origin);
            goods_detial_viewpager.setCurrentItem(position, false);
        }
        GoodsBasePager.mCurrentPosition = position;
    }

    /**
     * 获取头部轮播图片
     */
    private void initData() {
        try {
            Log.e("执行顺序", "YbDetialFragment_initData");
            String modelId = SpUtils.getString(APP.getAPP().getApplicationContext(), SpUtils.MODELID, "");
            Log.e(TAG, "modelId---->"+modelId );
            if (!TextUtils.isEmpty(modelId)) {
                Map playList = new HashMap();
                playList.put("modelId", modelId);
                NetUtils.Post(NetConstants.MODEL_BASE_INFO, playList, new MyCallBack<String>() {
                    @Override
                    public void onSuccess(String result) {
                        Log.e(TAG, "头部广告页"+result );
                        handViewPager(result);
                    }
                });
            } else {
                Log.e("执行顺序", "YbDetialFragment_initData");

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private int headViewNum = 0;
    private List<String> imageUrlList;
    private final int MSG_TIME = 3000111;
    private final int CHANGE_POSITION = 1232111;
    private int cur_index = 0;
    private int playTime = 0;
    private void handViewPager(String result) {
        imageUrlList = new ArrayList<>();
        try {
            JSONObject advice = new JSONObject(result);
            int status = advice.getInt("status");
            if (status == 1) {
                ModeImageList modeImageList = JsonForBean.getPerson(result, ModeImageList.class);

                List<ModelImageItem> imageList = modeImageList.getModelImageList();
                ModeBaseInfo modeBaseInfo = modeImageList.getModelBaseInfo();
                playTime = modeBaseInfo.getPlayTime();
                int size = imageList.size();
                        for (int i = 0; i < size; i++) {
                            File file = new File(FileConstants.IMAGE_CACHE_PATH + HandTextUtils.getFileName(imageList.get(i).getFileName()));
                            if (file.exists()) {
                        imageUrlList.add(file.getAbsolutePath());
                        handList(i, size);
                                Log.e(TAG, "handViewPager: ------->"+imageList.get(i).getFileName() );
                    } else {
                        downloadImageList(imageList.get(i).getFileName(), i, size);
                                Log.e(TAG, "handViewPager: ------->"+imageList.get(i).getFileName() );
                    }
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void handList(int i, int size) {
        if (i == size - 1) {
            if (imageUrlList.size() > 0) {
                initViewPager();
            }
        }
    }

    private void downloadImageList(String fileName, final int i, final int size) {
        Log.e("执行顺序", "YbDetialFragment_downloadImageList");

        NetUtils.DownLoadFile(fileName, FileConstants.IMAGE_CACHE_PATH + HandTextUtils.getFileName(fileName), new MyCallBack<File>() {
            @Override
            public void onSuccess(File result) {
                imageUrlList.add(result.getAbsolutePath());
                Log.e(TAG, "onSuccess-----downloadImageList---->" +result.getAbsolutePath());
                handList(i, size);
            }
            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                handList(i, size);
                Log.e(TAG, "onError--------->"+ex.getMessage().toString());
            }
        });
    }

    private void initViewPager() {
        Log.e("执行顺序", "YbDetialFragment_initViewPager");

        try {
            StoreHeadPagerAdapter storeHeadPagerAdapter = new StoreHeadPagerAdapter(imageUrlList);
            head_detial_viewpager.setAdapter(storeHeadPagerAdapter);
            headViewNum = storeHeadPagerAdapter.getCount();
            mhHandler.removeMessages(MSG_TIME);
            if (imageUrlList.size() >=1) {
                mhHandler.sendEmptyMessageDelayed(MSG_TIME,300);
            }else {
                iv_header.setVisibility(View.VISIBLE);
                head_detial_viewpager.setVisibility(View.GONE);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private Handler mhHandler;

    private Timer showTimer;
    private int showTime = 60;

    public void startTimer() {
        if (showTimer == null) {
            showTimer = new Timer();
        } else {
            showTimer.cancel();
            showTimer = null;
            showTimer = new Timer();
        }

        showTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                showTime--;
                Log.d("time","time"+showTime);
                if (showTime == 0) {
                    stopTimer();
                    mhHandler.sendEmptyMessage(CHANGE_POSITION);
                    System.gc();
                }
            }
        }, 1000, 1000);
    }

    public void stopTimer() {
        if (null != showTimer) {
            showTimer.cancel();
            showTimer = null;
        }
    }

    /**
     * 重置时间
     */
    public void resetTimer() {
        showTime = 60;
    }

    @Override
    public void onDestroyView() {
        Log.e("执行顺序", "YbDetialFragment_onDestroyView");
        if(mhHandler!=null){
            mhHandler.removeMessages(MSG_TIME);
            mhHandler = null;
        }
        head_detial_viewpager = null;
        stopTimer();
        System.gc();
        super.onDestroyView();
    }

}
